package com.search.controller;

import com.changgou.entity.Result;
import com.changgou.search.pojo.SkuInfo;
import com.changgou.util.Page;
import com.search.dao.ESManagerMapper;
import com.search.service.SearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.Set;

@Controller
@RequestMapping("/search")
public class SearchController
{
    @Autowired
    private ESManagerMapper esManagerMapper;
    @Autowired
    private SearchService searchService;
    @GetMapping("/list")
    public String search(@RequestParam Map<String,String> searchMap, Model model){
        StringBuilder url=new StringBuilder("/search/list");
        url.append("?");
        if (searchMap!=null&&searchMap.size()>0){
            for (String key : searchMap.keySet()) {
                if (!"sortRule".equals(key)&&!"sortField".equals(key)&&!"pageNum".equals(key)){
                    url.append(key).append("=").append(searchMap.get(key)).append("&");
                }
            }
        }
        String urlString = url.toString().substring(0, url.toString().length() - 1);
        model.addAttribute("url",urlString);
        this.handleSearchMap(searchMap);
        Map resultMap = searchService.searchcondition(searchMap);
        model.addAttribute("searchMap",searchMap);
         model.addAttribute("result",resultMap);
        Long totalPage =Long.parseLong( resultMap.get("totalpage").toString());
        int pageNum = Integer.parseInt(resultMap.get("pageNum").toString());
        int pageSize =Integer.parseInt( resultMap.get("pageSize").toString());
        Page<SkuInfo> page=new Page<SkuInfo>(totalPage,pageNum,pageSize);
        model.addAttribute("page",page);
         return "search";
    }
    private void handleSearchMap(Map<String, String> searchMap) {
        Set<Map.Entry<String, String>> entries = searchMap.entrySet();
        for (Map.Entry<String, String> entry : entries) {
            if (entry.getKey().startsWith("spec_")){
                searchMap.put(entry.getKey(),entry.getValue().replace("+","%2B"));
            }
        }
    }
    @GetMapping
    @ResponseBody
    private Map searches(@RequestParam Map<String,String> searchmap){
         this.handleSearchMap(searchmap);
        Map search = searchService.search(searchmap);
        List<SkuInfo> rows = (List<SkuInfo>)search.get("rows");
        return search;
    }
    @GetMapping("/condition")
    @ResponseBody
    private Map searchcondition(@RequestParam Map<String,String> searchmap){
        this.handleSearchMap(searchmap);
        Map search = searchService.searchcondition(searchmap);
        List<SkuInfo> rows = (List<SkuInfo>)search.get("rows");
        return search;
    }
}
